import { DropTarget } from 'react-dnd';

function getDropSpect(options = {}) {
  return {
    canDrop() {
      return true;
    },
    drop(props, monitor, component) {
      if (!monitor.isOver({ shallow: true })) {
        return;
      }
      const { editor, node } = props;
      let target = node;
      let index = node.nodes.size;
      if (editor.isVoid(node)) {
        const parent = editor.value.document.getParent(node.key);
        target = parent;
        index = parent.nodes.indexOf(node);
      }
      return { target, editor, index };
    }
  };
}

function dropCollect(connect, monitor) {
  const isOver = monitor.canDrop() && monitor.isOver({ shallow: true });
  return {
    connectDropTarget: connect.dropTarget(),
    isOver
  };
}

function DropDecorator(options = {}) {
  const { type = 'block' } = options;
  return Comp => {
    return DropTarget(type, getDropSpect(), dropCollect)(Comp);
  };
}

export default DropDecorator;
